<?php
namespace inkstones\db;
use inkstones\config\Config;

class Mysql{
	
	protected $tables='';
	protected $fields='';
	protected $where='';
	protected $order='';
	protected $limit='';
	protected $result='';
	protected $whereon='';
	protected $tablejoin='';
	
	public function query($sql){
		return mysql_query($sql);
	}
	
	/* 
	 *$where[0]=array('operator'=>'','field'=>'','val'=>'');
	 *where $where[0]['field'].$where[0].$where[0]
	*/
	public function where($fields=array(),$link_key=array()){
		foreach($link_key as $key=>$val){
			$this->where.=$fields[$key]['field'].$fields[$key]['operator'].$fields[$key]['val'].' '.$val;
		}
	}
	
	public function order($field,$sort){
		$this->order=' order by '.$field.' '.strtoupper($sort);
	}
	
	public function limit($start,$rows){
		$this->limit=' limit '.$start.','.$rows;
	}
	
	public function table($tname){
		$config=Config::get('mysql');
		$this->tables=$config['prefix']?$config['prefix'].'_'.$tname:$tname;
	}
	
	public function fields($field=array()){
		foreach($field as $k => $v){
			$this->fields.=$v.',';
		}
		$this->fields=trim($this->fields,',');
	}
	
	public function leftjoin($tname){
		$config=Config::get('mysql');
		$tname=$config['prefix']?$config['prefix'].'_'.$tname:$tname;
		$this->tablejoin='left join '.$tname.' '.$this->whereon;
	}
	
	public function on($arr=array()){
		$this->whereon.=$arr[0].'='.$arr[1];
	}
	
	public function select(){
		$this->table=$this->tablejoin?$this->table.' '.$this->tablejoin:$this->table;
		$sql='select '.$this->fields.' from '.$this->table.' '.$this->where.' '.$this->order.' '.$this->limit;
		
		$this->result=mysql_query($sql);
		
	}
	
	public function result($type=''){
		$array=array();
		if(!empty($this->result)){
			if(strtolower($type)=='assoc'){
				while($row=mysql_fetch_array($this->result,MYSQL_ASSOC)){
					$array[]=$row;
				}
			}
			elseif(strtolower($type)=='row'){
				while($row=mysql_fetch_array($this->result,MYSQL_NUM)){
					$array[]=$row;
				}
			}
			else{
				while($row=mysql_fetch_array($this->result)){
					$array[]=$row;
				}
			}
		}
		return $array;
	}
	
	public function update($field=array()){
		$update_field='';
		foreach($field as $k=>$v){
			$update_field.=$k.'='.$v.',';
		}
		$update_field=trim($update_field,',');
		
		$sql='update '.$this->table.' set '.$update_field.' '.$this->where;
		
		return $this->query($sql);
	}
	
	public function delete(){
		$sql='delete  from '.$this->table.' '.$this->where;
		
		return $this->query($sql);
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
}















?>